package com.atguigu.spzx.manager.interceptor;

import com.alibaba.fastjson.JSON;
import com.atguigu.spzx.common.handler.exception.SpzxException;
import com.atguigu.commom.utils.ThreadLocalUtil;
import com.atguigu.spzx.model.common.ResultCodeEnum;
import com.atguigu.spzx.model.entity.sys.SysUser;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * title:
 * author: zgl
 * date: 2023/12/27
 * description：
 */
@Component
public class SpzxInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    //可以用map存储，也可以用ThreadLocal存储
//    public static final ThreadLocal<SysUser> threadLocal = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放行预检请求
        String method = request.getMethod();
        if ("OPTIONS".equals(method.toUpperCase())) {
            return true;
        }
        String token = request.getHeader("token");
        if (StringUtils.isEmpty(token)) {
            throw new SpzxException(ResultCodeEnum.USER_NOT_LOGIN);
        }
        String json = redisTemplate.opsForValue().get("sys:user:login:" + token);
        if (StringUtils.isEmpty(json)) {
            throw new SpzxException(ResultCodeEnum.USER_NOT_LOGIN);
        }
        //共享数据userInfo业务层 ConcurrentHashMap<K,V>  键可以使用Thread.currentThread 或使用ThreadLocal
//        threadLocal.set(JSON.parseObject(json, SysUser.class));
        ThreadLocalUtil.threadLocal.set(JSON.parseObject(json, SysUser.class));
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //释放资源
        //清空数据
        ThreadLocalUtil.threadLocal.remove();
    }
}
